import { createRouter, createWebHistory } from 'vue-router'
import homeRouter from './homeRouter'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/Home/index.vue'),
      children: [...homeRouter],
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login/index.vue'),
      meta: {
        title: '登录'
      }
    },
    // 重定向到首页
    {
      path: '/index',
      redirect: '/'
    },
    // 404
    {
      path: '/:catchAll(.*)',
      component: () => import('@/components/common/404.vue'),
      meta: {
        title: '404'
      }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || '默认标题'

  // 检查是否需要登录权限
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    // 这里需要根据你的实际登录状态判断逻辑来修改
    const isAuthenticated = localStorage.getItem('token')
    if (!isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
